package kr.hkit.powerjava.chapter24.work;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;

import kr.hkit.powerjava.chapter24.work2.dao.*;

public class DepartmentDao implements InterfaceDao<Department> {
	private ArrayList<Department> lists;
	private static final String FILE_NAME = "DepartmentList.data";
	

	@Override
	public void insertItem(Department item) {
		if(!lists.contains(item)){
			lists.add(item);
		}else
			System.out.println("중복된 데이터");
	}

	@Override
	public void deleteItem(Department item) {//idx 삭제할 학번
		lists.remove(item);
	
	}

	@Override
	public void updateItem(Department item) {
		lists.set(lists.indexOf(item), item);
	}

	@Override
	public Department searchItem(Department item) {
		return lists.get(lists.indexOf(item));
	}

	@Override
	public void prnItemList(Comparator<Department> comp) {
		if(comp == null){
			Collections.sort(lists);
		}else{
			Collections.sort(lists, comp);
		}
		
		for(Department std : lists){
			System.out.println(std);
		}
	}

	@Override
	public void loadFile() {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(FILE_NAME)));
			lists = (ArrayList<Department>) ois.readObject(); 
		} catch (FileNotFoundException e) { //처음실행시 뜸. 파일 없으니까. 만들어줘야지
			try {
				new File(FILE_NAME).createNewFile(); //파일생성
				lists = new ArrayList<>(); //새로 입력할수있게끔 
			} catch (IOException e1) {}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null) try{ois.close();}catch(Exception e){}
		}
	}

	@Override
	public void saveFile() {
		ObjectOutputStream oos = null;
		try { //바로 덮어쓰는거임
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILE_NAME)));
			oos.writeObject(lists);
			oos.flush();
		}	catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (oos != null) try {oos.close();} catch(Exception e){}
		}
	}
}